//
//  AddMemberViewController.m
//  parent
//
//  Created by ci123 on 15/7/13.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "AddMemberViewController.h"
#import "PopUIManager.h"
#import "PhoneNumberChecker.h"
#import "NetWorkManager.h"
#import "DBManager.h"
#import "JsonUtil.h"
#import "UserDao.h"

@interface AddMemberViewController ()

@end

@implementation AddMemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _shadeView.hidden = YES;
    _shadeView.alpha = 0.6;
    _menuView.hidden = YES;
    
    self.navigationController.navigationBarHidden = NO;
    self.title = @"添加家人";
    _addMemberButton.layer.cornerRadius = 5;
    
    _nickName.userInteractionEnabled = NO;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickEvent)];
    tap.numberOfTapsRequired = 1;
    _contactList.userInteractionEnabled = YES;
    [_contactList addGestureRecognizer:tap];
    
    _grandfatherButton.layer.cornerRadius = 4;
    _grandfatherButton.layer.masksToBounds = YES;
    _grandfatherButton.layer.borderColor = UIColorMake(252,74,74).CGColor;
    _grandfatherButton.layer.borderWidth = 1;
    
    _grandmotherButton.layer.cornerRadius = 4;
    _grandmotherButton.layer.masksToBounds = YES;
    _grandmotherButton.layer.borderColor = UIColorMake(252,74,74).CGColor;
    _grandmotherButton.layer.borderWidth = 1;
    
    _fatherButton.layer.cornerRadius = 4;
    _fatherButton.layer.masksToBounds = YES;
    _fatherButton.layer.borderColor = UIColorMake(252,74,74).CGColor;
    _fatherButton.layer.borderWidth = 1;
    
    _motherButton.layer.cornerRadius = 4;
    _motherButton.layer.masksToBounds = YES;
    _motherButton.layer.borderColor = UIColorMake(252,74,74).CGColor;
    _motherButton.layer.borderWidth = 1;
    
    _laolaoButton.layer.cornerRadius = 4;
    _laolaoButton.layer.masksToBounds = YES;
    _laolaoButton.layer.borderColor = UIColorMake(252,74,74).CGColor;
    _laolaoButton.layer.borderWidth = 1;
    
    _laoyeButton.layer.cornerRadius = 4;
    _laoyeButton.layer.masksToBounds = YES;
    _laoyeButton.layer.borderColor = UIColorMake(252,74,74).CGColor;
    _laoyeButton.layer.borderWidth = 1;
    
    _otherButton.layer.cornerRadius = 4;
    _otherButton.layer.masksToBounds = YES;
    _otherButton.layer.borderColor = UIColorMake(252,74,74).CGColor;
    _otherButton.layer.borderWidth = 1;
    
    _cancelButton.layer.cornerRadius = 5;
}

- (IBAction)nickNameButton:(id)sender {
    NSLog(@"click..");
    _shadeView.hidden = NO;
    _menuView.hidden = NO;
}

- (IBAction)addMember:(id)sender {
    NSLog(@"%@,%@,%@",_nickName.text,_name.text,_phoneNumber.text);
    if (_nickName.text.length == 0 || _name.text.length == 0 || _phoneNumber.text.length == 0) {
        [[PopUIManager getInstanse] popAlertView:self title:@"提示" message:@"信息不完整" cancelButtonTitle:@"确定"];
    }else if (![PhoneNumberChecker isValidNumber:_phoneNumber.text]){
        [[PopUIManager getInstanse] popAlertView:self title:@"提示" message:@"手机格式错误" cancelButtonTitle:@"确定"];
    }else{
        //提交，请求服务器
        NSString *phone = _phoneNumber.text;
        NSString *nick_name = _nickName.text;
//        NSString *frole =
        NSString *fid = [NSString stringWithFormat:@"%ld",(long)[[UserDao getInstance]getCurrentBaby].fid];
        NSString *uid = [NSString stringWithFormat:@"%ld",(long)[[UserDao getInstance]getUserId]];
        NSString *token = [[UserDao getInstance]getAccessToken];
        
        
        NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:phone, @"phone", uid, @"uid", nick_name , @"nickname", _role_type, @"frole", fid, @"fid", token,@"token",nil]];
        
        PopUIManager *popUIMgr = [PopUIManager getInstanse];
        [popUIMgr showWaitingUI:self.view];
        
        [[NetWorkManager getInstanse] requestURLAsynMessage:@"ADD_FAMILY" data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) { //连接失败
                debugLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
                NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
                [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
            }else{//连接成功，判断是否有数据返回
                NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                NSLog(@"服务器返回StateCode:%ld", (long)responseCode);
                
                if (data) {
                    NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                    NSLog(@"数据字典: %@", dict);
                    
                    if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                        //登录失败，弹窗提示
                        NSString *ret_msg;
                        switch ([[dict objectForKey:@"retCode"] integerValue]) {
                            case 1:{
                                ret_msg = @"Success";
                                break;
                            }
                            case 10006:{
                                ret_msg= @"手机号码不合法";
                                break;
                            }case 10007:{
                                ret_msg= @"用户已经存在";
                                break;
                            }
                            default:{
                                ret_msg= @"未知错误";
                                break;
                            }
                        }
                        if (![ret_msg isEqual:@"Success"]) {
                            [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                        }else{
                            _modal_view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT)];
                            _modal_view.backgroundColor = [UIColor blackColor];
                            _modal_view.alpha = 0.6;
                            [[UIApplication sharedApplication].keyWindow addSubview:_modal_view];
                            
                            CGFloat width_length = APP_SCREEN_WIDTH *0.5;
                            
                            _white_view = [[UIView alloc]initWithFrame:CGRectMake((APP_SCREEN_WIDTH-width_length)/2, (APP_SCREEN_HEIGHT - width_length*0.6)/2, width_length, width_length*0.6)];
                            _white_view.layer.cornerRadius = 5;
                            _white_view.backgroundColor = [UIColor whiteColor];
                            
                            CGFloat imgWidth = _white_view.size.width * 0.3;
                            UIImageView *mail = [[UIImageView alloc]initWithFrame:CGRectMake((_white_view.size.width - imgWidth)/2, (_white_view.size.height - imgWidth*0.5)/3, imgWidth, imgWidth*0.5)];
                            [mail setImage:[UIImage imageNamed:@"mail"]];
                            [_white_view addSubview:mail];
                            
                            UILabel *label = [[UILabel alloc]init];
                            label.text = @"亲友邀请已发送";
                            label.font = [UIFont systemFontOfSize:13];
                            [label sizeToFit];
                            label.textColor = UIColorMake(252, 74, 74);
                            label.center = CGPointMake(_white_view.size.width/2, mail.bottom + 20);
                            [_white_view addSubview:label];
                            
                            [[UIApplication sharedApplication].keyWindow addSubview:_white_view];
                            
                            [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timeOver) userInfo:nil repeats:NO];
                            
                            
                        }
                    }else{
                        [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                }
            }
            [popUIMgr removeWaitingUI];
        }];
        
    }
}

- (void)timeOver {
    _modal_view.hidden = YES;
    _white_view.hidden = YES;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)clickEvent {
    NSLog(@"contact people");
    _peoplePicker = [[ABPeoplePickerNavigationController alloc]init];
    _peoplePicker.peoplePickerDelegate = self;
    _peoplePicker.displayedProperties = [NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonPhoneProperty]];
    [self presentViewController:_peoplePicker animated:YES completion:nil];
}

// Called after a property has been selected by the user.
// 8.0之后才会调用
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person {
    ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    if (firstName==nil) {
        firstName = @"";
    }
    NSString *lastName=(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (lastName==nil) {
        lastName = @"";
    }
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
        NSString *aPhone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMulti, i);
        [phones addObject:aPhone];
    }
    NSString *phone = @"";
    if (phones.count > 0) {
        phone = [phones objectAtIndex:0];
    }
    
    _name.text = [NSString stringWithFormat:@"%@%@", firstName, lastName];
    _phoneNumber.text = phone;
}

// 8。0之前才会调用
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicke shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    if (firstName==nil) {
        firstName = @"";
    }
    NSString *lastName=(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (lastName==nil) {
        lastName = @"";
    }
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
        NSString *aPhone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMulti, i);
        [phones addObject:aPhone];
    }
    NSString *phone = @"";
    if (phones.count > 0) {
        phone = [phones objectAtIndex:0];
    }
    _name.text = [NSString stringWithFormat:@"%@%@", firstName, lastName];
    _phoneNumber.text = phone;
    [_peoplePicker dismissViewControllerAnimated:YES completion:nil];
    return NO;  
}
- (IBAction)fatherClick:(id)sender {
    _shadeView.hidden = YES;
    _menuView.hidden = YES;
    _nickName.text = @"爸爸";
    _role_type = @"1";
}

- (IBAction)motherClick:(id)sender {
    _shadeView.hidden = YES;
    _menuView.hidden = YES;
    _nickName.text = @"妈妈";
    _role_type = @"2";
}
- (IBAction)yeyeClick:(id)sender {
    _shadeView.hidden = YES;
    _menuView.hidden = YES;
    _nickName.text = @"爷爷";
    _role_type = @"3";
}
- (IBAction)nainaiClick:(id)sender {
    _shadeView.hidden = YES;
    _menuView.hidden = YES;
    _nickName.text = @"奶奶";
    _role_type = @"4";
}
- (IBAction)laolaoClick:(id)sender {
    _shadeView.hidden = YES;
    _menuView.hidden = YES;
    _nickName.text = @"姥姥";
    _role_type = @"6";
}
- (IBAction)laoyeClick:(id)sender {
    _shadeView.hidden = YES;
    _menuView.hidden = YES;
    _nickName.text = @"姥爷";
    _role_type = @"5";
}
- (IBAction)otherClick:(id)sender {
    _shadeView.hidden = YES;
    _menuView.hidden = YES;
    _nickName.text = @"其他";
    _role_type = @"7";
}
- (IBAction)cancelClick:(id)sender {
    _shadeView.hidden = YES;
    _menuView.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
